import http from '@ohos.net.http';
import { initInfo } from "./log";

export interface RequestOption extends http.HttpRequestOptions{
  url: string,
}

let log = initInfo('http');

export function request(option: RequestOption){
  let httpRequest = http.createHttp();
//  httpRequest.on("headersReceive", (header)=>{
//    log(`header: ${JSON.stringify(header)}`);
//  })
  let url = option.url || "";
  let method = option.method || http.RequestMethod.GET;

  let header = {
    "Content-Type": "application/json"
  };
  let extraData = option.extraData || {};
  let expectDataType = option.expectDataType || http.HttpDataType.OBJECT;

  let usingCache = true;
  let priority = 1;
  let connectTimeout = 5000;
  let usingProtocol = http.HttpProtocol.HTTP1_1;

   return httpRequest.request(url, {
      method,
      header,
      extraData,
      expectDataType,
      usingCache,
      priority,
      connectTimeout,
      usingProtocol
  })
}

export function httpGet(option){
    let url = option.url;
    let method = http.RequestMethod.GET;
    return request({url, method});
}

export function httpPost(option){
    let url = option.url;
    let method = http.RequestMethod.POST
    let extraData = {...option.data};
    let expectDataType = option.dataType || http.HttpDataType.OBJECT;
    return request({url, method, extraData, expectDataType});
}
